package com.retail.lottery.colalottery.service.cola;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.retail.lottery.colalottery.constant.ColaHttpUrlConfig;
import com.retail.lottery.colalottery.entity.OrderCallback;
import com.retail.lottery.colalottery.enums.ErrorCodeEnum;
import com.retail.lottery.colalottery.enums.OrderCallbackSyncStatusEnum;
import com.retail.lottery.colalottery.exception.BusinessException;
import com.retail.lottery.colalottery.service.PlatformTenantClientService;
import com.retail.lottery.colalottery.vo.request.GetLotteryTimesRequest;
import com.retail.lottery.colalottery.vo.request.SendMessageNoticeRequest;
import com.retail.lottery.colalottery.vo.response.GetLotteryTimesResponse;
import com.retail.lottery.colalottery.vo.response.GetSetupInfoResponse;
import com.retail.lottery.colalottery.vo.response.SendMessageNoticeResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class ColaClientService {

    @Resource
    private PlatformTenantClientService platformTenantClientService;
    @Resource
    private ColaHttpUrlConfig colaHttpUrlConfig;
    @Value("${api-client-setupId}")
    private String lotterySetupId;
    /**
     * 读取活动信息
     * @param setupId
     * @param buCode
     * @return
     */
    public GetSetupInfoResponse getSetupInfo(String buCode, String setupId){
        //log.info("开始获取可乐活动信息,活动id：{}", setupId);
        try{
            String accessToken = platformTenantClientService.getAccessToken(setupId);
            if(StringUtils.isBlank(accessToken)){
                throw new BusinessException(ErrorCodeEnum.GET_ACCESS_TOKEN_FAIL);
            }
            if(StringUtils.isBlank(buCode) || StringUtils.isBlank(setupId)){
                throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", accessToken);
            String setupInfoUrl = colaHttpUrlConfig.getSetupInfoUrl(buCode, setupId);
            String response = HttpRequest.get(setupInfoUrl)
                    .headerMap(headers, true) // 添加Header
                    .execute()
                    .body();

            log.info("可乐活动setupId数据：{},结果:{}", setupId, JSONObject.toJSONString(response));
            if(Objects.nonNull(response)){
                //log.info("订可乐活动setupId数据：{},成功", setupId);
                return JSON.parseObject(response, GetSetupInfoResponse.class);
            }else{
                //log.info("订可乐活动setupId数据：{},失败", setupId);
                throw new BusinessException(ErrorCodeEnum.POST_FAIL);
            }
        }catch (Exception e){
            log.error("获取可乐活动信息异常,活动id：{}", setupId, e);
        }
        return null;
    }

    /**
     * 读取活动抽奖次数信息
     * @param buCode
     * @return
     */
    public GetLotteryTimesResponse queryLotteryTimesInfo(String buCode, GetLotteryTimesRequest request){
        log.info("开始获取可乐活动登录人抽奖次数,buCode:{},request：{}", buCode, request);
        try{
            String accessToken = platformTenantClientService.getAccessToken(lotterySetupId);
            if(StringUtils.isBlank(accessToken)){
                throw new BusinessException(ErrorCodeEnum.GET_ACCESS_TOKEN_FAIL);
            }
            if(StringUtils.isBlank(buCode) || Objects.isNull(request)){
                throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", accessToken);
            // 4. 发送POST请求
            HttpResponse response = HttpRequest.post(colaHttpUrlConfig.queryLotteryTimesUrl(buCode))
                    .headerMap(headers, true) // 添加Headers
                    .body(JSONUtil.toJsonStr(request)) // JSON参数
                    .execute();
            log.info("可乐活动buCode数据：{},获取抽奖次数结果:{}", buCode, JSONObject.toJSONString(response.body()));
            if(Objects.nonNull(response) && response.getStatus() == HttpStatus.OK.value()){
                //log.info("可乐活动buCode数据：{},获取抽奖次数成功", buCode);
                return JSON.parseObject(response.body(), GetLotteryTimesResponse.class);
            }else{
                //log.error("可乐活动buCode数据：{},获取抽奖次数失败", buCode);
                throw new BusinessException(ErrorCodeEnum.POST_FAIL);
            }
        }catch (Exception e){
            log.error("可乐活动buCode数据异常，buCode：{}", buCode);
        }
        return null;
    }

    /**
     * 发送消息订阅消息信息
     * @param buCode
     * @return
     */
    public Boolean sendMessageNotice(String buCode,String setupId, SendMessageNoticeRequest request){
        log.info("发送订阅消息,buCode:{},request：{}", buCode, request);
        try{
            String accessToken = platformTenantClientService.getAccessToken(setupId);
            if(StringUtils.isBlank(accessToken)){
                throw new BusinessException(ErrorCodeEnum.GET_ACCESS_TOKEN_FAIL);
            }
            if(StringUtils.isBlank(buCode) || Objects.isNull(request)){
                throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
            }

            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", accessToken);
            // 4. 发送POST请求
            HttpResponse response = HttpRequest.post(colaHttpUrlConfig.messageNoticeUrl(buCode))
                    .headerMap(headers, true) // 添加Headers
                    .body(JSONUtil.toJsonStr(request)) // JSON参数
                    .execute();

            log.info("发送订阅消息：{},响应：{},响应结果:{}", buCode, response.getStatus(), JSONObject.toJSONString(response.body()));
            if(response.getStatus() == HttpStatus.OK.value()){
                //log.info("发送订阅消息：{},获取返回结果成功", buCode);
                return Boolean.TRUE;
            }else{
                //log.info("发送订阅消息：{},获取返回结果失败", buCode);
                throw new BusinessException(ErrorCodeEnum.POST_FAIL);
            }
        }catch (Exception e){
            log.error("发送订阅消息异常，buCode：{}", buCode);
        }
        return Boolean.FALSE;
    }

}
